package com.library.controller;

import com.library.dto.BorrowDTO;
import com.library.entity.BorrowRecord;
import com.library.service.BorrowRecordService;
import com.library.vo.PageVO;
import com.library.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/borrow-records")
@Slf4j
public class BorrowRecordController {

    @Autowired
    private BorrowRecordService borrowRecordService;

    @GetMapping
    @PreAuthorize("hasRole('ADMIN')")
    public ResultVO<PageVO<BorrowRecord>> getBorrowRecords(
            @RequestParam(defaultValue = "1") Long current,
            @RequestParam(defaultValue = "10") Long size,
            @RequestParam(required = false) Long userId
    ) {
        try {
            PageVO<BorrowRecord> result = borrowRecordService.getBorrowRecordPage(current, size, userId);
            return ResultVO.success(result);
        } catch (Exception e) {
            log.error("查询借阅记录失败: {}", e.getMessage());
            return ResultVO.error("查询失败: " + e.getMessage());
        }
    }

    @GetMapping("/my")
    public ResultVO<PageVO<BorrowRecord>> getMyBorrowRecords(
            @RequestParam(defaultValue = "1") Long current,
            @RequestParam(defaultValue = "10") Long size
    ) {
        try {
            PageVO<BorrowRecord> result = borrowRecordService.getBorrowRecordPage(current, size, null);
            return ResultVO.success(result);
        } catch (Exception e) {
            log.error("查询我的借阅记录失败: {}", e.getMessage());
            return ResultVO.error("查询失败: " + e.getMessage());
        }
    }

    @PostMapping("/borrow")
    public ResultVO<String> borrowBook(@RequestBody BorrowDTO borrowDTO) {
        try {
            boolean result = borrowRecordService.borrowBook(borrowDTO.getUserId(), borrowDTO.getBookId(), borrowDTO.getBorrowDays());
            if (result) {
                log.info("用户 {} 借阅书籍 {}", borrowDTO.getUserId(), borrowDTO.getBookId());
                return ResultVO.success("借阅成功");
            } else {
                return ResultVO.error("借阅失败");
            }
        } catch (Exception e) {
            log.error("借阅书籍失败: {}", e.getMessage());
            return ResultVO.error("借阅失败: " + e.getMessage());
        }
    }

    @PostMapping("/return")
    public ResultVO<String> returnBook(@RequestParam Long recordId) {
        try {
            boolean result = borrowRecordService.returnBook(recordId);
            if (result) {
                log.info("归还书籍成功 - 记录ID: {}", recordId);
                return ResultVO.success("归还成功");
            } else {
                return ResultVO.error("归还失败");
            }
        } catch (Exception e) {
            log.error("归还书籍失败: {}", e.getMessage());
            return ResultVO.error("归还失败: " + e.getMessage());
        }
    }
}
